package com.fxb.learn;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 本地变量类型推测demo
 *
 * @author fangjiaxiaobai
 * @date 2021-11-08 23:05
 */
public class localVariableDemo {

    public static void main(String[] args) {
        test3();
    }

    /**
     * 使用var定义。
     */
    public static void test1() {
        var str1 = "local variable type interface";
        String str2 = "local variable type interface";
        System.out.println(str1 == str2); //true
    }


    /**
     * 简化泛型声明
     */
    public static void test2() {
        var lists = new ArrayList<Map<String, List<String>>>();

        for (var item : lists) {
            var entries = item.entrySet();
            for (var entry : entries) {
                String key = entry.getKey();
                var values = entry.getValue();
                for (var value : values) {
                    System.out.println(value);
                }
            }
        }
    }

    /**
     * lambda参数
     * 从Java 11开始，lambda参数也允许使用var关键字：
     */
    public static void test3() {
        Predicate<String> predNotNull = (var a) -> a != null && !a.isBlank();


        String strAfterFilter = Stream.of("I", "", "love", " ", "my", "wife", null, "very", "much")
                .filter(predNotNull)
                .collect(Collectors.joining(" "));
        System.out.println(strAfterFilter); //I love my wife very much
    }

    /**
     * 不兼容的类型是不能重新赋值
     */
    public static void test4() {
        var str = "I: hi. single dog";
        str = "U: wang wang wang";
//        str = 1.111111;
    }

    /**
     * 只要编译器无法推断出变量类型，就会编译错误！
     */
    public static void test5() {
//        var var1;
//        var var2 = null;
//        var var3 = () -> System.out.println("local veriable type interface");
    }

}
